#include <errno.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include <sstream>

#include "Player.h"
#include "Exception.h"
#include "NetWorkInterface.h"

using namespace std;

string NetWorkInterface::sendMessageGame(string message, Player &player)  throw (Exception)
{
	cout << endl <<"--------------------sendMessageGame-------------------"<< endl;
	cout << player.getName().toStdString() << "--" << player.getIp().toStdString() << ":" << player.getPort().toStdString() << endl;
	cout << message << endl;
	cout << "----------------------------------------------------"<< endl<<endl; ;
	// allocation de variable /
	int sock_serv_fd = -1;
	struct sockaddr_in serv_addr;
	char request[1000];
	char response[50];
	for(int i=0;i<50;i++) response[i] = '\0';

	in_addr_t numeric_addr;
	size_t request_len = sizeof(request);

	string sreponde = "";

	// envoi message au joueur + la réponse
	try
	{
		// construit la socket /
		if ((sock_serv_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
		{
			std::cout << "CLIENT: socket error" << std::endl;
			throw Exception("CLIENT: socket error");
		}

		// convertit l'adresse décimale pointée en adresse numérique /
		if (inet_pton(AF_INET, player.getIp().toStdString().c_str(), &numeric_addr) <= 0)
		{
			cout << "CLIENT: inet_pton error" << std::endl;
			throw Exception("CLIENT: inet_pton error");
		}

		// remplit la structure sockaddr_in /
		serv_addr.sin_family = AF_INET;
		serv_addr.sin_addr.s_addr = numeric_addr;
		serv_addr.sin_port = 	htons( atoi( player.getPort().toStdString().c_str() ) );

		// connecte la socket au serveur /
		if (connect(sock_serv_fd, (struct sockaddr*) &serv_addr, sizeof(struct sockaddr_in)) == -1)
		{
			cout << "Connexion joueur perdu (errno = "<< errno <<")" << endl;
			close(sock_serv_fd);
			throw Exception("CLIENT: connect error");
		}

		strcpy(request,message.c_str());

		// emission message /
		if (write(sock_serv_fd, request, sizeof( request) ) != request_len)
		{
			std::cout << "write error" << std::endl;
			throw Exception("write error");
		}

		// Attente et Lecture du message retour /
		while (read(sock_serv_fd, response, 50) != 0)
		{
			sreponde = response;
		}

		cout << endl <<"--------------------getMessageGame-------------------"<< endl;
		cout << player.getName().toStdString() << " repond (" << sreponde << ")"<< endl;
		cout << "-------------------------------------------------------"<< endl<<endl ;

		// close /
		close(sock_serv_fd);
	}
	catch(Exception e)
	{
		cout << "Kill application : Les joueurs ne répond plus aux questions du dealer " << endl;
		exit(0);
	}
	return sreponde;
}
